package composer.gui;

import java.io.IOException;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextBox;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.MIDIControl;

import composer.base.Note;
import composer.base.NotesOffThread;
import composer.base.NotesOnThread;
import composer.base.Track;

public class MainScreen {

	private Vector tracks;
	private int bpm;
	
	private Form mainForm;
	private List tracksList;
	
	private Command exitCommand;
	private Command menuCommand;
	
	public MainScreen(){
		this.tracks = new Vector();
		this.bpm = 60;
		
		menuCommand = new Command("New Track", Command.SCREEN, 1);
		exitCommand = new Command("Exit", Command.EXIT, 0);
		
		mainForm = new Form("new song");
		tracksList = new List("Tracks", List.EXCLUSIVE);
		//mainForm.append();
		
		Track t1 = new Track((byte)0);
		Track t2 = new Track((byte)1);
		
		t1.addNote(new Note(30, 100, 0, 1));
		t1.addNote(new Note(34, 100, 2, 1));
		t1.addNote(new Note(37, 100, 4, 1));
		t1.addNote(new Note(36, 100, 6, 1));
		
		t2.addNote(new Note(60, 100, 8, 4));
		t2.addNote(new Note(64, 100, 10, 4));
		t2.addNote(new Note(67, 100, 12, 4));
		t2.addNote(new Note(66, 100, 14, 4));
		
		this.tracks.addElement(t1);
		this.tracks.addElement(t2);
	}
	
	public void playAll(){
		try {
			MIDIControl midiControl = getMIDIControl();

			Thread notesOn = new NotesOnThread(tracks, midiControl, bpm);
			Thread notesOff = new NotesOffThread(tracks, midiControl, bpm);
			
			notesOn.start();
			notesOff.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private MIDIControl getMIDIControl() throws IOException, MediaException {
		Player p = Manager.createPlayer(Manager.MIDI_DEVICE_LOCATOR);
		p.realize();
		
		MIDIControl midiControl = (MIDIControl) p.getControl("javax.microedition.media.control.MIDIControl");
		p.prefetch();
		return midiControl;
	}

	public void enter() {
		// TODO Auto-generated method stub
		
	}
	
}
